package com.woniuxy.cq.phrase3.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.cq.phrase3.common.Result;
import com.woniuxy.cq.phrase3.common.ValidationUtil;
import com.woniuxy.cq.phrase3.controller.form.ChangeUserRoleForm;
import com.woniuxy.cq.phrase3.controller.form.ProjectForm;
import com.woniuxy.cq.phrase3.controller.form.UserForm;
import com.woniuxy.cq.phrase3.controller.form.UserFormLogin;
import com.woniuxy.cq.phrase3.entity.Country;
import com.woniuxy.cq.phrase3.entity.Industry;
import com.woniuxy.cq.phrase3.entity.Role;
import com.woniuxy.cq.phrase3.entity.User;
import com.woniuxy.cq.phrase3.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
import java.util.Set;

/**
 * 用户控制层
 * @author 胡八一
 * @date 2020/09/07 10:39
 */
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册user
     * @param userForm
     * @param result
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody@Valid UserForm userForm, BindingResult result){
        log.info("注册接收的参数为:{}",userForm);
        String extract = ValidationUtil.extract(result);
        if(extract != null){return Result.fail("500","参数异常:"+extract);}
        try { userService.register(userForm); return Result.success("注册成功");}catch (Exception e){
            e.printStackTrace();
            return Result.fail("500","注册失败:"+e.getMessage());
        }
    }

    /**
     * 登陆user
     * @param userFormLogin
     * @param result
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody@Valid UserFormLogin userFormLogin, HttpSession session, BindingResult result){
        System.out.println("进入登陆");
        log.info("登陆接收的参数为:{}",userFormLogin);
        String extract = ValidationUtil.extract(result);
        log.info("登陆后返回的数据：{}",extract);
        if(extract != null){return Result.fail("500","参数异常:"+extract);}
        try {
            Result resultl = userService.login(userFormLogin);
            if(resultl.isSuccess()){
                //登陆成功 存入session
                User user = (User)resultl.getData();
                session.setAttribute("userId",((User) resultl.getData()).getUserId());
                System.out.println("登陆成功存入session的id:"+((User) resultl.getData()).getUserId());
                //根据userid 查询 该用户的角色 返回给前端
                String rolesById = userService.findRolesByUserId(user.getUserId());
                return Result.success(rolesById);
            }
            return Result.fail("500","登陆失败");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("500","登陆失败");
        }
    }

    /**
     * 登陆时 当用户焦点离开时 检测用户名是否存在
     * @param username
     * @return
     */
    @PostMapping("checkByUserName")
    public Result checkByUserName(String username){
        log.info("登陆验证用户名参数为:{}",username);
        return userService.checkByUserName(username);
    }


    /**
     * 项目申请
     * @param projectForm
     * @param result
     * @return
     */
    @PostMapping("applicationProject")
    public Result applicationProject(@RequestBody@Valid ProjectForm projectForm,HttpSession session,BindingResult result){
        log.info("项目申请接收的参数为:{}",projectForm);
        String extract = ValidationUtil.extract(result);
        if(extract != null){return Result.fail("500","参数异常:"+extract);}
        //判断结果
        try {
            projectForm.setProjectUserId((Integer) session.getAttribute("userId"));
            userService.applicationProject(projectForm);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("500","注册失败");
        }
    }

    //获取产业类型的方法
    @PostMapping("getAllIndustry")
    public Result getAllIndustry(){
        log.info("获取产业数据");
        List<Industry> list = userService.getAllIndustry();
        return Result.success(list);
    }

    //获取区县的方法
    @PostMapping("getAllCountry")
    public Result getAllCountry(){
        log.info("获取区县数据");
        List<Country> list = userService.getAllCountry();
        return Result.success(list);
    }


    /**
     * 删除用户
     * @return
     */
    @GetMapping("deleteUserById")
    public Result deleteUserById(Integer userId){
        log.info("删除User获取的参数:{}",userId);
        try {
            userService.deleteUserById(userId);
            return Result.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("500","删除失败");
        }
    }

    /**
     * 修改用户
     * @return
     */
    @PostMapping("updateUserByUserForm")
    public Result updateUserByUserForm(@RequestBody UserForm userForm){
        log.info("更新User获取的userForm:{}",userForm);
        try {
            int i = userService.updateUserByUserForm(userForm);
            if(i == 0){
                return Result.success("更新成功");
            }else if(i == 1){
                return Result.fail("500","用户名已存在");
            }else if(i == 2){
                return Result.fail("500","号码格式不对");
            }
           return Result.fail("500","系统故障");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("500","更新失败");
        }
    }

    //分页查询 User 可带条件
    @PostMapping("queryAllUByPage")
    public Result queryAllByPage(@RequestBody UserForm userForm){
        log.info("分页查询的参数userForm:{}",userForm);
        try {
            PageInfo<UserForm> pageInfo = userService.queryAllByPage(userForm);
            return Result.success(pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("500","查询失败");
        }
    }

    /**
     * 修改用户的权限
     * @param changeUserRoleForm
     * @return
     */
    @PostMapping("changeRole")
    public Result changeRole(@RequestBody ChangeUserRoleForm changeUserRoleForm){
        log.info("修改用户权限参数位:{}",changeUserRoleForm);
        try {
            userService.changeRole(changeUserRoleForm);
            return Result.success("修改权限成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("500","修改权限失败");
        }
    }

    /**
     * 获取所有的角色
     * @return
     */
    @PostMapping("getAllRole")
    public Result getAllRole(){
        log.info("获取所有角色");
        List<Role> allRole = userService.getAllRole();
        return Result.success(allRole);
    }

    /**
     * 获取用户的 角色
     * @param userId
     * @return
     */
    @GetMapping("findRolesByUserId")
    public Result findRolesByUserId(Integer userId){
        String rolesById = userService.findRolesByUserId(userId);
        return Result.success(rolesById);
    }


}
